<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FacarauthenticationController extends Controller
{

    /**
     * 私家车辆认证列表
     * User:@hang
     */
    public function privateindex(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['b.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['b.me_uid','=',$param['me_uid']];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['b.me_phone|b.me_nick_name','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $whehe[] = ['a.name','like',"%{$param['name']}%"];
        }
        if (isset($param['car_name']) && !empty($param['car_name'])) {
            $whehe[] = ['a.car_name|a.car_all_name','like',"%{$param['car_name']}%"];
        }
        if (isset($param['car_vin']) && !empty($param['car_vin'])) {
            $whehe[] = ['a.car_vin','=',$param['car_vin']];
        }
        if (isset($param['car_model']) && !empty($param['car_model'])) {
            $whehe[] = ['a.car_model','like',"%{$param['car_model']}%"];
        }
        if (isset($param['add_admin_id']) && $param['add_admin_id'] != '') {
            if($param['add_admin_id'] == 1){
                $whehe[] = ['a.img','=','直接破圈'];
            }
            if($param['add_admin_id'] == 2){
                $whehe[] = ['a.add_admin_id','=',0];
                $whehe[] = ['a.img','neq','直接破圈'];
            }
            if($param['add_admin_id'] == 3){
                $whehe[] = ['a.add_admin_id','neq',0];
            }
        }
        $whehetime = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
        }

        if (isset($param['fmember_id']) && !empty($param['fmember_id'])) {
            $whehe[] = ['d.member_id','=',$param['fmember_id']];
        }
        if (isset($param['fme_uid']) && !empty($param['fme_uid'])) {
            $whehe[] = ['d.me_uid','like',"%{$param['fme_uid']}%"];
        }
        if (isset($param['fme_phone']) && !empty($param['fme_phone'])) {
            $whehe[] = ['d.me_phone','like',"%{$param['fme_phone']}%"];
        }
        if (isset($param['fme_nick_name']) && !empty($param['fme_nick_name'])) {
            $whehe[] = ['d.me_nick_name','like',"%{$param['fme_nick_name']}%"];
        }

        $whehe[] = ['a.type','=',1];
        $data = Db::table('fa_car_authentication')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->join("fa_circle_list c",'a.circle_id = c.id','LEFT')
            ->join("fa_member d",'b.me_parent = d.member_id','LEFT')
            ->where($whehe)
            ->where($whehetime)
            ->field('a.*,b.me_uid,b.me_phone,b.me_nick_name,b.me_sex,b.me_circle_sbnum,b.me_is_circle,b.me_car_type,b.me_carname,b.me_circle_id,b.me_circle_url,b.me_circle_str,b.me_is_real,b.me_realname,b.me_realidcard,c.circle_name,d.member_id as f_member_id,d.me_uid as f_me_uid,d.me_phone as f_me_phone,d.me_nick_name as f_me_nick_name')
            ->order('a.add_time desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $adminid = $this->uid;
        $data->each(function ($v, $k)use($adminid) {
            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
                $v['f_me_phone'] = hide_phone_number($v['f_me_phone']);
            }
            if($v['me_carname'] == '买圈车主' && empty($v['add_admin_id'])){
                $v['add_admin_id_word'] = '通过破圈';
            }else{
                if(empty($v['add_admin_id'])){
                    $v['add_admin_id_word'] = '通过行驶证';
                }else{
                    $v['add_admin_id_word'] = '管理端开通';
                }
            }

            switch($v['type']){
                case '1': $v['type_word'] = '私家车辆';break;
                case '2': $v['type_word'] = '企业车辆';break;
                case '3': $v['type_word'] = '运营车辆';break;
            }
            $v['car_money_word'] = $v['car_money'].'万';
            if($v['add_admin_id'] != 0){
                $v['name'] = $v['name'].'(虚拟)';
                $v['me_carname'] = $v['me_carname'].'(虚拟)';
                $v['car_vin'] = $v['car_vin'].'(虚拟)';
                $v['car_model'] = $v['car_model'].'(虚拟)';
                $v['car_money'] = $v['car_money'].'(虚拟)';
                $v['car_money_word'] = $v['car_money_word'].'(虚拟)';
            }
            $v['add_time'] = date('Y-m-d H:i',$v['add_time']);
            $v['f_member_id'] = empty($v['f_member_id'])?0:$v['f_member_id'];
            return $v;
        });
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }


    /**
     * 清除私家车辆认证
     * User:@hang
     */
    public function delprivate($id)
    {
        $IndexTableModel = New IndexTableModel();
        $carAuthenticationInfo = $IndexTableModel->getFind('fa_car_authentication',"`id` = '{$id}'",'id,member_id');
        if(empty($carAuthenticationInfo)){
            return admin_error('抱歉，车辆认证信息查询错误',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:delprivate'.$carAuthenticationInfo['member_id'];	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $res = $this->delmembercircle($carAuthenticationInfo['member_id']);
        if($res != 200){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error($res,URL_CLOSE_REFRESH);
        }
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('清除用户车辆认证信息成功',URL_CLOSE_REFRESH);
    }



    /**
     * 清除用户的车辆认证信息
     * User:@hang
     */
    public function delmembercircle($member_id)
    {
        $ctime = time();
        $IndexTableModel = New IndexTableModel();
        //清空用户表车辆相关信息
        $IndexTableModel->editInfo('fa_member',"`member_id` = '{$member_id}'",array('me_is_circle'=>0,'me_car_type'=>0,'me_carname'=>'','me_circle_id'=>0,'me_circle_url'=>'','me_circle_str'=>''));
        //恢复用户破圈信息
        $me_circle_str = '';
        $recharge_circle_order_list = $IndexTableModel->getList('fa_recharge_circle_order',"`member_id` = '{$member_id}'",'id,member_id,circle_id','id asc');
        if(!empty($recharge_circle_order_list)){
            foreach ($recharge_circle_order_list as $k=>$v){
                $me_circle_str .= $v['circle_id'].',';
            }
        }
        $me_circle_str = trim($me_circle_str,',');
        $IndexTableModel->editInfo('fa_member',"`member_id` = '{$member_id}'",array('me_circle_str'=>$me_circle_str));
        //清空用户车辆认证信息
        $IndexTableModel->delOne('fa_car_authentication',"`member_id` = '{$member_id}'");
        //增加服务通知
        $IndexTableModel->addInfo('fa_news_service',array('type'=>10,'member_id'=>$member_id,'j_member_id'=>$member_id,'g_table'=>'fa_car_authentication','g_id'=>0,'content'=>'抱歉，您于 '.date('Y年m月d日 H:i:s',$ctime).' 车辆认证被清除，您可以再次前往【圈子模块】或【个人中心】进行车辆认证。','is_read'=>0,'add_time'=>$ctime));
        return 200;
    }



    /**
     * 企业车辆认证列表
     * User:@hang
     */
    public function firmindex(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['b.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['b.me_uid','=',$param['me_uid']];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['b.me_phone|b.me_nick_name','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $whehe[] = ['a.name','like',"%{$param['name']}%"];
        }
        if (isset($param['car_name']) && !empty($param['car_name'])) {
            $whehe[] = ['a.car_name|a.car_all_name','like',"%{$param['car_name']}%"];
        }
        if (isset($param['car_vin']) && !empty($param['car_vin'])) {
            $whehe[] = ['a.car_vin','=',$param['car_vin']];
        }
        if (isset($param['car_model']) && !empty($param['car_model'])) {
            $whehe[] = ['a.car_model','like',"%{$param['car_model']}%"];
        }
        if (isset($param['add_admin_id']) && $param['add_admin_id'] != '') {
            if($param['add_admin_id'] == 0){
                $whehe[] = ['a.add_admin_id','=',0];
            }else{
                $whehe[] = ['a.add_admin_id','neq',0];
            }
        }
        $whehetime = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
        }
        if (isset($param['is_pass']) && !empty($param['is_pass'])) {
            $whehe[] = ['a.is_pass','=',$param['is_pass']];
        }
        if (isset($param['state']) && $param['state'] != '') {
            $whehe[] = ['a.state','=',$param['state']];
        }

        $whehe[] = ['a.type','neq',1];
        $data = Db::table('fa_car_authentication')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->join("fa_circle_list c",'a.circle_id = c.id','LEFT')
            ->where($whehe)
            ->where($whehetime)
            ->field('a.*,b.me_uid,b.me_phone,b.me_nick_name,b.me_sex,b.me_circle_sbnum,b.me_is_circle,b.me_car_type,b.me_carname,b.me_circle_id,b.me_circle_url,b.me_circle_str,b.me_is_real,b.me_realname,b.me_realidcard,c.circle_name')
            ->order('a.state asc,a.add_time desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $data->each(function ($v, $k) {

            if($v['me_carname'] == '买圈车主' && empty($v['add_admin_id'])){
                $v['add_admin_id_word'] = '通过破圈';
            }else{
                if(empty($v['add_admin_id'])){
                    $v['add_admin_id_word'] = '通过行驶证';
                }else{
                    $v['add_admin_id_word'] = '管理端开通';
                }
            }

            switch($v['type']){
                case '1': $v['type_word'] = '私家车辆';break;
                case '2': $v['type_word'] = '企业车辆';break;
                case '3': $v['type_word'] = '运营车辆';break;
            }
            $v['car_money_word'] = $v['car_money'].'万';
            if($v['add_admin_id'] != 0){
                $v['name'] = $v['name'].'(虚拟)';
                $v['car_name'] = $v['car_name'].'(虚拟)';
                $v['car_vin'] = $v['car_vin'].'(虚拟)';
                $v['car_model'] = $v['car_model'].'(虚拟)';
                $v['car_money'] = $v['car_money'].'(虚拟)';
                $v['car_money_word'] = $v['car_money_word'].'(虚拟)';
            }
            $v['add_time'] = date('Y-m-d H:i',$v['add_time']);
            switch($v['is_pass']){
                case '1': $v['is_pass_word'] = '无需审核，直接通过';break;
                case '2': $v['is_pass_word'] = '需要审核';break;
            }
            switch($v['state']){
                case '0': $v['state_word'] = '待审核';break;
                case '1': $v['state_word'] = '已通过';break;
                case '2': $v['state_word'] = '已拒绝';break;
            }
            return $v;
        });
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }


    /**
     * 通过企业车辆认证
     * User:@hang
     */
    public function passfirm($id)
    {
        $IndexTableModel = New IndexTableModel();
        $carAuthenticationInfo = $IndexTableModel->getFind('fa_car_authentication',"`id` = '{$id}'",'*');
        if(empty($carAuthenticationInfo)){
            return admin_error('抱歉，车辆认证信息查询错误',URL_CLOSE_REFRESH);
        }
        if($carAuthenticationInfo['type'] != 2){
            return admin_error('企业认证车辆才可审核',URL_CLOSE_REFRESH);
        }
        if($carAuthenticationInfo['state'] != 0){
            return admin_error('此企业认证车辆信息已经审核过',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:passfirm'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        //增加用户表车辆相关信息
        $qcinfo = $IndexTableModel->getFind('fa_circle_list',"id = '{$carAuthenticationInfo['circle_id']}'",'id,circle_name,circle_url');
        if(empty($qcinfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('圈层信息查询失败',URL_CLOSE_REFRESH);
        }
        //恢复用户破圈信息
        $me_circle_str = $carAuthenticationInfo['circle_id'].',';
        $recharge_circle_order_list = $IndexTableModel->getList('fa_recharge_circle_order',"`member_id` = '{$carAuthenticationInfo['member_id']}'",'id,member_id,circle_id','id asc');
        if(!empty($recharge_circle_order_list)){
            foreach ($recharge_circle_order_list as $k=>$v){
                if($carAuthenticationInfo['circle_id'] != $v['circle_id']){
                    $me_circle_str .= $v['circle_id'].',';
                }
            }
        }
        $me_circle_str = trim($me_circle_str,',');
        $IndexTableModel->editInfo('fa_member',"`member_id` = '{$carAuthenticationInfo['member_id']}'",array('me_is_circle'=>1,'me_car_type'=>2,'me_carname'=>$carAuthenticationInfo['car_name'],'me_circle_id'=>$carAuthenticationInfo['circle_id'],'me_circle_url'=>$qcinfo['circle_url'],'me_circle_str'=>$me_circle_str));
        //增加服务通知
        $IndexTableModel->addInfo('fa_news_service',array('type'=>9,'member_id'=>$carAuthenticationInfo['member_id'],'j_member_id'=>$carAuthenticationInfo['member_id'],'g_table'=>'fa_car_authentication','g_id'=>$carAuthenticationInfo['id'],'content'=>'恭喜，您于 '.date('Y年m月d日 H:i:s',$ctime).' 企业车辆认证已通过，您的车辆【'.$carAuthenticationInfo['car_name'].'】，进入圈层【'.$qcinfo['circle_name'].'】。','is_read'=>0,'add_time'=>$ctime));
        //修改认证信息状态
        $res = $IndexTableModel->editInfo('fa_car_authentication',"`id` = '{$id}'",array('state'=>1,'sh_admin_id'=>$this->uid,'sh_content'=>'企业车辆认证通过','sh_time'=>$ctime));
        if(empty($res)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改认证信息状态失败',URL_CLOSE_REFRESH);
        }
        //查询是否有上级
        $memberInfo = $IndexTableModel->getFind('fa_member',"member_id = '{$carAuthenticationInfo['member_id']}'",'member_id,me_parent');
        if(empty($memberInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户信息查询失败',URL_CLOSE_REFRESH);
        }
        if(!empty($memberInfo['me_parent'])){
            $parentMemberInfo = $IndexTableModel->getFind('fa_member',"member_id = '{$memberInfo['me_parent']}'",'member_id,me_invitation_rewards');
            if(empty($parentMemberInfo)){
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('用户父级信息查询失败',URL_CLOSE_REFRESH);
            }
            if($parentMemberInfo['me_invitation_rewards'] == 1){
                //执行邀请奖励
                $Common = New Common();
                $resInvite = $Common->actionInviteRewards($memberInfo['me_parent'],$memberInfo['member_id']);
                if($resInvite != 200){
                    $Redis_Lock->unlock($otc_sell_key);	//释放锁
                    return admin_error('邀请奖励失败',URL_CLOSE_REFRESH);
                }
            }
            //更新邀请榜
            $Common->setRankingYq($memberInfo['me_parent'],1);
        }
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('企业认证车辆通过成功',URL_CLOSE_REFRESH);
    }

    /**
     * 拒绝企业车辆认证
     * User:@hang
     */
    public function refusefirm($id)
    {
        $IndexTableModel = New IndexTableModel();
        $carAuthenticationInfo = $IndexTableModel->getFind('fa_car_authentication',"`id` = '{$id}'",'*');
        if(empty($carAuthenticationInfo)){
            return admin_error('抱歉，车辆认证信息查询错误',URL_CLOSE_REFRESH);
        }
        if($carAuthenticationInfo['type'] != 2){
            return admin_error('企业认证车辆才可审核',URL_CLOSE_REFRESH);
        }
        if($carAuthenticationInfo['state'] != 0){
            return admin_error('此企业认证车辆信息已经审核过',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:refusefirm'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        //增加服务通知
        $IndexTableModel->addInfo('fa_news_service',array('type'=>10,'member_id'=>$carAuthenticationInfo['member_id'],'j_member_id'=>$carAuthenticationInfo['member_id'],'g_table'=>'fa_car_authentication','g_id'=>$carAuthenticationInfo['id'],'content'=>'抱歉，您于 '.date('Y年m月d日 H:i:s',$ctime).' 企业车辆认证未通过，您可以前往【圈子模块】或【个人中心】进行车辆认证。','is_read'=>0,'add_time'=>$ctime));
        //修改认证信息状态
        $res = $IndexTableModel->editInfo('fa_car_authentication',"`id` = '{$id}'",array('state'=>2,'sh_admin_id'=>$this->uid,'sh_content'=>'企业车辆认证拒绝','sh_time'=>$ctime));
        if(empty($res)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改认证信息状态失败',URL_CLOSE_REFRESH);
        }
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('企业认证车辆拒绝成功',URL_CLOSE_REFRESH);
    }

    /**
     * 清除企业车辆认证
     * User:@hang
     */
    public function delfirm($id)
    {
        $IndexTableModel = New IndexTableModel();
        $carAuthenticationInfo = $IndexTableModel->getFind('fa_car_authentication',"`id` = '{$id}'",'*');
        if(empty($carAuthenticationInfo)){
            return admin_error('抱歉，车辆认证信息查询错误',URL_CLOSE_REFRESH);
        }
        if($carAuthenticationInfo['type'] != 2){
            return admin_error('企业认证车辆才可清除',URL_CLOSE_REFRESH);
        }
        if($carAuthenticationInfo['state'] != 0){
            return admin_error('已经通过的企业认证车辆才可清除',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        $IndexTableModel = New IndexTableModel();
        //清空用户表车辆相关信息
        $IndexTableModel->editInfo('fa_member',"`member_id` = '{$carAuthenticationInfo['member_id']}'",array('me_is_circle'=>0,'me_car_type'=>0,'me_carname'=>'','me_circle_id'=>0,'me_circle_url'=>'','me_circle_str'=>''));
        //恢复用户破圈信息
        $me_circle_str = '';
        $recharge_circle_order_list = $IndexTableModel->getList('fa_recharge_circle_order',"`member_id` = '{$carAuthenticationInfo['member_id']}'",'id,member_id,circle_id','id asc');
        if(!empty($recharge_circle_order_list)){
            foreach ($recharge_circle_order_list as $k=>$v){
                $me_circle_str .= $v['circle_id'].',';
            }
        }
        $me_circle_str = trim($me_circle_str,',');
        $IndexTableModel->editInfo('fa_member',"`member_id` = '{$carAuthenticationInfo['member_id']}'",array('me_circle_str'=>$me_circle_str));
        //清空用户车辆认证信息
        $IndexTableModel->delOne('fa_car_authentication',"`member_id` = '{$carAuthenticationInfo['member_id']}'");
        //增加服务通知
        $IndexTableModel->addInfo('fa_news_service',array('type'=>10,'member_id'=>$carAuthenticationInfo['member_id'],'j_member_id'=>$carAuthenticationInfo['member_id'],'g_table'=>'fa_car_authentication','g_id'=>0,'content'=>'抱歉，您于 '.date('Y年m月d日 H:i:s',$ctime).' 车辆认证被清除，您可以再次前往【圈子模块】或【个人中心】进行车辆认证。','is_read'=>0,'add_time'=>$ctime));
        return 200;
    }




}
